package controllers

import (
	"IrisService/models"

	"github.com/jinzhu/gorm"
	"github.com/kataras/iris/v12"
)

type GEntityController struct {
	*baseController
}

func NewGEntityController(db *gorm.DB) *GEntityController {
	props := []string{
		"_apis",
		"id/#id",
		"label/#label",
		"topics",
		"topic/#topic",
		"POST:"}
	item := &baseController{
		entry: "ChangeLog",
		db:    db,
		model: models.ChangeLogItem{},
		props: props}

	return &GEntityController{item}
}

func (c *GEntityController) GetIdBy(id uint) iris.Map {
	if id < 1 {
		return c.Fail()
	} else {
		item := new(models.GEntity)
		c.db.First(item, id)
		return c.Rise(item)
	}
}

func (c *GEntityController) GetTopics() iris.Map {
	var items []string
	rows, _ := c.db.Table(c.model.TableName()).Select("topic").Group("topic").Rows()
	for rows.Next() {
		var item string
		rows.Scan(&item)
		items = append(items, item)
	}
	return c.GenTopics(items)
}

func (c *GEntityController) GetLabelBy(label string) iris.Map {
	if len(label) == 0 {
		return c.Fail()
	} else {
		items := new([]models.GEntity)
		c.db.Where("label LIKE ?", "%"+label+"%").Find(items)
		return c.GenDetails(items)
	}
}

func (c *GEntityController) GetTopicBy(topic string) iris.Map {
	if len(topic) == 0 {
		return c.Fail()
	} else {
		items := new([]models.GEntity)
		c.db.Where("topic=?", topic).Find(items)
		return c.GenTopic(topic, items)
	}
}

func (c *GEntityController) Post(ctx iris.Context) iris.Map {
	item := new(models.GEntity)
	if err := ctx.ReadJSON(item); err != nil {
		return c.Fail()
	} else {
		return c.Rise(c.db.Create(item).RowsAffected)
	}
}
